package WordFrequent;

import com.sun.istack.internal.Nullable;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class Onestep {


   static Map<String,Integer> map = new TreeMap<String,Integer>();

   //分割字符串并将其存储到map中
 static  public void splist(String words) {
     String tmp = ""; //设置存储单词的字符串
        map.clear();

     //将字符串和次数存入map中
     for (int i = 0; i < words.length(); i++) {
         if ((words.charAt(i) < 123 && words.charAt(i) > 96) || words.charAt(i) == '\'') {
             tmp += words.charAt(i);
             if (i == words.length()-1){

                 if (!map.containsKey(tmp) ) {
                     map.put(tmp, 1);
                 } else {
                     Integer times = map.get(tmp);
                     map.put(tmp, times+1);
                 }break;
             }
         } else if ( tmp != "" ) {

             if (!map.containsKey(tmp)) {
                 map.put(tmp, 1);
             } else {
                 Integer times = map.get(tmp);
                 map.put(tmp, times+1);
             }
             tmp = "";
         } else {
             tmp = "";
         }
     }
 }

    public static List<Map.Entry<String,Integer>> sort(String words){


        //构建比较器
        Comparator<Map.Entry<String,Integer>> mycomparator = new Comparator<Map.Entry<String,Integer>>() {
            @Override
            public int compare(Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2) {
                if (o1.getValue() != o2.getValue()){
                    return o2.getValue()- o1.getValue();
                }
                else {
                    return o1.getKey().charAt(0) - o2.getKey().charAt(0);
                }
            }
        };

        splist(words);
        //将字符串以单词形式分割并存储至List数组中
        List<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
        Collections.sort(list,mycomparator);
            return list;
    }
    public static void print1(String words){

        List<Map.Entry<String,Integer>> list   =     sort(words);

        for (int i = 0 ;i <list.size(); i++){
            System.out.printf("%s \t %d \t\n",list.get(i).getKey(),list.get(i).getValue());
        }
        System.out.println("==========================================================================");
    }

}
